package com.ikun.yummy.utils.mail;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

import java.io.File;

import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;

public class SendMailUtil {

    public interface CallBack{
        void onSuccess();
        void onFailed();
    }
    public static void send(SenderEmailInfo senderInfo, String toAdd, String title, String txt, final File file){
        send(senderInfo,toAdd,title,txt,file,null);
    }
    public static void send(SenderEmailInfo senderInfo, String toAdd, String title, String txt, final File file, final CallBack callBack){
        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            CommandMap.setDefaultCommandMap(mc);
        final MailInfo mailInfo = creatMail(senderInfo,toAdd,title,txt);
        final MailSender sms = new MailSender();
        @SuppressLint("HandlerLeak") final Handler handler = new Handler(){
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (callBack!=null){
                    if (msg.what==0){
                        callBack.onSuccess();
                    }else {
                        callBack.onFailed();
                    }
                }
            }
        };
        new Thread(() -> {
            if (file!=null){
                boolean success = sms.sendFileMail(mailInfo, file);
                handler.sendEmptyMessage(success?0:1);
            }else {
                boolean success =sms.sendTextMail(mailInfo);
                handler.sendEmptyMessage(success?0:1);
            }
        }).start();
    }
    private static MailInfo creatMail(SenderEmailInfo info, String toAdd, String title, String txt) {
        final MailInfo mailInfo = new MailInfo();
        mailInfo.setMailServerHost(info.getMailServerHost());
        mailInfo.setMailServerPort(info.getMailServerPort());
        mailInfo.setUserName(info.getFromAddress()); // 你的邮箱地址
        mailInfo.setPassword(info.getPassword());// 您的邮箱密码
        mailInfo.setFromAddress(info.getFromAddress()); // 发送的邮箱
        mailInfo.setToAddress(toAdd); // 发到哪个邮件去
        mailInfo.setSubject(title); // 邮件主题
        mailInfo.setContent(txt); // 邮件文本
        return mailInfo;
    }
}
